package top.yunmouren.areamusic.event;

import top.yunmouren.areamusic.AreaMusic;
import top.yunmouren.areamusic.config.AreaDto;
import top.yunmouren.areamusic.exception.PlayerNullException;
import top.yunmouren.areamusic.music.MusicTag;
import top.yunmouren.areamusic.player.PlayerBridge;
import top.yunmouren.areamusic.utils.MusicUtil;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent;

import java.util.List;

public class PlayerTeleportListener extends MusicUtil implements Listener {
    private final AreaMusic plugin;

    public PlayerTeleportListener(AreaMusic plugin) {
        super(plugin);
        this.plugin = plugin;
    }

    @EventHandler
    public void onEvent(PlayerTeleportEvent event) {
        try {
            PlayerBridge playerBridge = new PlayerBridge(event.getPlayer(), this.plugin);
            MusicTag musicTag = playerBridge.getPlayerMusicTag();
            Location to;
            List areaDtos;
            if (musicTag != null) {
                to = event.getFrom();
                if (to.getWorld() != null) {
                    areaDtos = this.getInsideList(to.getWorld().getName(), to.getX(), to.getY(), to.getZ());
                    if (areaDtos.size() != 0) {
                        areaDtos.forEach((item) -> {
                            if (item.toString().equals(musicTag.getAreaUUID())) {
                                playerBridge.getPlayer().stopSound(musicTag.getMusicURL());
                                playerBridge.clearPlayerMusicTag();
                            }

                        });
                    }
                }
            }

            to = event.getTo();
            if (to == null) {
                return;
            }

            AreaDto targetArea;
            if (musicTag == null) {
                if (to.getWorld() != null) {
                    areaDtos = this.getInsideList(to.getWorld().getName(), to.getX(), to.getY(), to.getZ());
                    if (areaDtos.size() != 0) {
                        targetArea = this.selectMostImportantArea(areaDtos);
                        this.play(playerBridge, targetArea);
                    }
                }
            } else if (to.getWorld() != null) {
                areaDtos = this.getInsideList(to.getWorld().getName(), to.getX(), to.getY(), to.getZ());
                if (areaDtos.size() != 0) {
                    targetArea = this.selectMostImportantArea(areaDtos);
                    if (targetArea.getPriority().getValue() > musicTag.getPriority().getValue()) {
                        this.play(playerBridge, targetArea);
                    }
                }
            }
        } catch (PlayerNullException var7) {
        }

    }
}